package com.hjq.demo.aop

import android.app.Activity
import com.flyjingfish.android_aop_annotation.ProceedJoinPoint
import com.flyjingfish.android_aop_annotation.base.BasePointCut
import com.hjq.demo.manager.ActivityManager
import com.hjq.demo.other.PermissionCallback
import com.hjq.permissions.XXPermissions
import com.tencent.bugly.crashreport.CrashReport
import timber.log.Timber

class PermissionsCut : BasePointCut<Permissions> {
    override fun invoke(
        joinPoint: ProceedJoinPoint,
        annotation: Permissions //annotation就是你加到方法上的注解
    ): Any? {
        val target = joinPoint.getTarget() // 获取被拦截的对象实例
        val activity = if (target is Activity) {
            target // 如果目标实例是Activity类型，直接赋值
        } else {
            // 如果目标不是Activity，则尝试通过其他方式获取当前的Activity实例
            ActivityManager.getInstance().getTopActivity()
        }
        if ((activity == null) || activity.isFinishing || activity.isDestroyed) {
            Timber.e("The activity has been destroyed and permission requests cannot be made")
        } else {
            requestPermissions(joinPoint, activity, annotation.value)
        }
        return null
    }

    private fun requestPermissions(
        joinPoint: ProceedJoinPoint,
        activity: Activity,
        permissions: Array<out String>
    ) {
        XXPermissions.with(activity)
            .permission(*permissions)
            .request(object : PermissionCallback() {
                override fun onGranted(permissions: MutableList<String?>, all: Boolean) {
                    if (all) {
                        try {
                            // 获得权限，执行原方法
                            joinPoint.proceed()
                        } catch (e: Throwable) {
                            CrashReport.postCatchedException(e)
                        }
                    }
                }
            })
    }
}